package com.dtp.common.pattern.filter;

/**
 * 调用链工厂
 *
 * @author yanhom
 * @since 1.0.8
 *
 * @remark muse
 **/
public final class InvokerChainFactory {
    private InvokerChainFactory() {}

    @SafeVarargs
    public static<T> InvokerChain<T> buildInvokerChain(Invoker<T> target, Filter<T>... filters) {
        InvokerChain<T> invokerChain = new InvokerChain<>(); // 创建调用链
        Invoker<T> last = target; // 待调用的目标对象

        // 倒序执行filters里的过滤器
        for (int i = filters.length - 1; i >= 0; i--) {
            Invoker<T> next = last;
            Filter<T> filter = filters[i];
            // last=filter4(filter3(filter2(filter1(next))))
            last = context -> filter.doFilter(context, next);
        }

        // 执行顺序是：filter4——>filter3——>filter2——>filter1——>next
        invokerChain.setHead(last);
        return invokerChain;
    }
}


